package com.etrans.util.sso;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.etrans.domain.SSOParam;

import net.sf.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Component
public class AuthUtils {

	
	private String appuser="06"; 
	private String appkey="3I0wtFXNnKcgLfYbKDWpDkfj0A0oOm";
	
	private OkHttpClient client;

	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss'Z'");

	public String post(String url, Map<String, Object> params) throws IOException {
		
		String randomcode = RandomStringUtils.random(10, true, true);
		Calendar now = Calendar.getInstance();
		String timestamp = sdf.format(now.getTime());
		
		String data = StringUtils.join(appuser, randomcode, timestamp);
		String encodekey = DigestUtils.sha256Hex(StringUtils.join(data, "{", appkey, "}"));

		JSONObject object = JSONObject.fromObject(params);
		String paramData = StringUtils.join(object.toString(), "&", appkey);
		String signature = DigestUtils.md5Hex(paramData);

		JSONObject json = JSONObject.fromObject(object);
		RequestBody body = RequestBody.create(JSON, json.toString());
		Request request = new Request.Builder().url(url).addHeader("appuser", appuser)
				.addHeader("randomcode", randomcode).addHeader("timestamp", timestamp).addHeader("encode", encodekey)
				.addHeader("sign", signature).addHeader("sign", signature).addHeader("clientip", "")
				.addHeader("Content-Type", "application/json").post(body).build();
		Response response = client.newCall(request).execute();

		return response.body().string();
	}

	public String getAppuser() {
		return appuser;
	}

	public void setAppuser(String appuser) {
		this.appuser = appuser;
	}

	public String getAppkey() {
		return appkey;
	}

	public void setAppkey(String appkey) {
		this.appkey = appkey;
	}

	public OkHttpClient getClient() {
		return client;
	}

	public void setClient(OkHttpClient client) {
		this.client = client;
	}

	
	
}
